package etxt2db.annotators;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import edu.cmu.minorthird.text.*;
import etxt2db.api.ClassificationModel;
import etxt2db.corpus.CompleteTextLabels;
import etxt2db.corpus.NoTokenSpan;

import com.aliasi.chunk.*;

public class RegexClassificationModel extends ClassificationModel implements Serializable {
	
	private RegExChunker chunker;
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -4418090350192270143L;

	public RegexClassificationModel(String regex, String type) {
		// This class extends RegExChunker (Lingpipe) and its constructor is basically
		// a call for the RegExChunker constructor. We need to give the regex for this 
		// model and the type. The score is ignored in this case.
		chunker = new RegExChunker(regex,type,1);
    }
	
	@Override
	public void annotate(MonotonicTextLabels arg0) {
		//We need an iterator to navigate through the Document Spans
		System.out.println("Starting now!");
		long time = System.currentTimeMillis();
		Iterator<Span> iter = arg0.getTextBase().documentSpanIterator();
		while(iter.hasNext()){
			Span span = iter.next();
			//The chunking interface of Lingpipe uses strings, so we need to
			//convert our documents to strings.
			Chunking chunking = chunker.chunk(span.asString());

			for (Chunk chunk : chunking.chunkSet()) {
				//Each chunk gives us the start and end of the span we want to
				//annotate
	            int start = chunk.start();
	            int end = chunk.end();
	            
	            //Luckily it is what we want in the Span interface
	            NoTokenSpan newSpan=new NoTokenSpan(span,span.getLoChar()+start,span.getLoChar()+end);
	            
	            //We add a new Span to the TexLabels
				((CompleteTextLabels)arg0).addNoTokenToType(newSpan,chunk.type());
	        }
		}
		System.out.println((System.currentTimeMillis()-time) + " miliseconds passed");
	}

	@Override
	public TextLabels annotatedCopy(TextLabels arg0) {
		//Just create a new TextLabels (copy) before annotate
		CompleteTextLabels copy = new CompleteTextLabels(arg0.getTextBase());
		annotate(copy);
		//Return the new TextLabels
		return copy;
	}

	@Override
	public String explainAnnotation(TextLabels arg0, Span arg1) {
		//Not important in this work... but necessary to implement the interface
		return "";
	}
	
	public static ClassificationModel getOptimizedClassificationModel(String regex, String type){
		if(regex.matches("[a-zA-Z0-9&' \\-]+(\\|[a-zA-Z0-9&' \\-]+)*")){
			System.out.println("Detectei uma mudan�a");
			String[] terms = regex.split("\\|");
			List<String> dictionary = Arrays.asList(terms);
			return new DictionaryClassificationModel(dictionary,type,true);
		}else{
			System.out.println("Nao Detectei uma mudan�a");
			return new RegexClassificationModel(regex,type);
		}
	}
}
